package cn.chenxing.module.query.controller;

import cn.chenxing.domain.dto.TrackData;
import cn.chenxing.domain.dto.TrackLine;
import cn.chenxing.domain.dto.TrackPoint;
import cn.chenxing.domain.dto.TrackTable;
import cn.chenxing.domain.threadlocal.ThreadData;
import cn.chenxing.domain.util.DateUtil;
import cn.chenxing.domain.util.DialogBuilderUtil;
import cn.chenxing.module.query.service.QueryService;
import cn.chenxing.utils.TableUtil;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @Description 位置查询控制层
 * @Author maogen.ymg
 * @Date 2020/4/15 13:32
 */
@Lazy
@FXMLController
@Slf4j
public class QueryLocationController implements Initializable {

    @FXML
    private WebView webView;

    @FXML
    private BorderPane borderPane;

    @FXML
    private Label tipLabel;

    @Autowired
    private QueryService queryService;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        // 获取页面路径
        String mainUrl = getClass().getResource("/html/locationHint.html").toExternalForm();
        // 初始化
        webView.getEngine().load(mainUrl);
    }

    @FXML
    public void query() {
        if(ThreadData.get().getTrackData() == null) {
            DialogBuilderUtil.showPositiveAlert(tipLabel, "无法进行查询", "还没导入数据，请选择文件菜单进行导入");
            return;
        }
        // 位置
        String location = (String) webView.getEngine().executeScript("getLocation()");
        String scopeStr = (String) webView.getEngine().executeScript("getScope()");
        double scope = Double.parseDouble(scopeStr);
        if(StringUtils.isBlank(location)) {
            DialogBuilderUtil.showPositiveAlert(tipLabel, "提示", "请输入地点");
            return;
        }

        // 通过百度API逆地理编码获取
        TrackPoint trackPoint = queryService.getCoordinate(location);

        // 显示在表格上
        TableUtil.importTableView(borderPane, getTableData(trackPoint, scope), false);

    }

    @FXML
    public void clear() {
        webView.getEngine().executeScript("clearLocation()");
        borderPane.getChildren().clear();
        borderPane.setCenter(tipLabel);
    }

    /**
     * 获取表格数据
     * @return List<TrackTable>
     */
    private List<TrackTable> getTableData(TrackPoint trackPointLeft, double scope) {
        List<TrackTable> trackTableList = new ArrayList<>();

        //-----------计算查询点的经纬度范围----------
        //地球半径千米
        double r = 6371.137;
        // 改成千米单位
        double dis = scope/1000;
        double dLng = 2*Math.asin(Math.sin(dis/(2*r))/Math.cos(trackPointLeft.getLatitude()*Math.PI/180));
        //角度转为弧度 
        dLng = dLng*180/Math.PI;
        double dLat = dis/r;
        dLat = dLat*180/Math.PI;
        double minLat = trackPointLeft.getLatitude()-dLat;
        double maxLat = trackPointLeft.getLatitude()+dLat;
        double minLng = trackPointLeft.getLongitude() -dLng;
        double maxLng = trackPointLeft.getLongitude() + dLng;

        // 用户数据
        List<TrackLine> trackLineList = ThreadData.get().getTrackData().getTrackLineList();
        for(TrackLine trackLine : trackLineList) {
            for(TrackPoint trackPoint : trackLine.getTrackPointList()) {
                boolean lon = trackPoint.getLongitude() >= minLng && trackPoint.getLongitude() <= maxLng;
                boolean lat = trackPoint.getLatitude() >= minLat && trackPoint.getLatitude() <= maxLat;
                if(lon && lat) {
                    TrackTable trackTable = new TrackTable();
                    trackTable.setId(trackLine.getId())
                            .setLongitude(trackPoint.getLongitude())
                            .setLatitude(trackPoint.getLatitude())
                            .setTime(DateUtil.timeStamp2Date(trackPoint.getTimeStamp(), null))
                            .setSpeed(trackPoint.getSpeed());
                    trackTableList.add(trackTable);
                }
            }

        }
        // 保存为公有数据
        TrackData trackData = ThreadData.get().getTrackData();
        trackData.setTrackLineList(trackLineList);
        ThreadData.get().setTrackData(trackData);
        return trackTableList;
    }

}
